package com.jacky.datasource.config;

import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.jacky.datasource.constants.SourceConstants;
import com.jacky.datasource.datasource.SourceProperties;
import org.springframework.context.annotation.Configuration;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDatasourceLoading {

    private final SourceProperties sp;

    public DynamicDatasourceLoading(SourceProperties sourceProperties) {
        this.sp = sourceProperties;
    }

    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return new AbstractJdbcDataSourceProvider(sp.getUrl(), sp.getUsername(), sp.getPassword()) {
            @Override
            protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
                ResultSet resultSet = statement.executeQuery(SourceConstants.SELECT_SQL);
                Map<String, DataSourceProperty> retMap = new HashMap<>();
                while (resultSet.next()) {
                    String dbSign = resultSet.getString(SourceConstants.Details.SIGN.code());
                    String username = resultSet.getString(SourceConstants.Details.USERNAME.code());
                    String password = resultSet.getString(SourceConstants.Details.PASSWORD.code());
                    String url = resultSet.getString(SourceConstants.Details.URL.code());
                    String driver = resultSet.getString(SourceConstants.Details.DRIVER_CLASS.code());

                    DataSourceProperty dp = new DataSourceProperty();
                    dp.setUrl(url);
                    dp.setUsername(username);
                    dp.setPassword(password);
                    dp.setDriverClassName(driver);
                    retMap.putIfAbsent(dbSign, dp);
                }
                return retMap;
            }
        };
    }


}
